var path = require('path');
var webpack = require('webpack');
var config = require('./app/config');
var glob = require('glob');
var _ = require('lodash');

// 跟目录
var ROOT_PATH = path.resolve(__dirname);
// 代码目录
var APP_PATH = path.resolve(ROOT_PATH, 'app');
// 编译目录
var BUILD_PATH = path.resolve(ROOT_PATH, 'dest');
// node模块目录
var NODE_MODULE_DIR = path.resolve(ROOT_PATH,'node_module');

// 获取指定路径下的入口文件
function getEntries(globPath) {
  var files = glob.sync(globPath),
    entries = {};

  files.forEach(function(filepath) {
    // 取倒数第二层(view下面的文件夹)做包名
    var split = filepath.split('/');
    var name = split[split.length - 2];

    entries[name] = filepath;
  });

  return entries;
}

function getEntryAndPlugin() {
  var entries = getEntries(APP_PATH + '/routes/**/index.jsx');
  var entrys = {}
  _.map(entries, (filepath, name) => {
    name = name.toLowerCase();
    // 每个页面生成一个entry，如果需要HotUpdate，在这里修改entry
    entrys[name] = filepath;
  })
  entrys["vendor"] = [// 把第三方的依赖打成一个包js包
    'babel-polyfill',
    //'es5-shim',
    //'console-polyfill',
    'react',
    'react-dom',
    //'react-router',
    'react-redux',
    'redux',
    'redux-thunk',
    'lodash',
    'isomorphic-fetch',
    'redux-promise-middleware',
  ]

  var plugins = []
  plugins.push(new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify(config.env)
    }
  }))
  plugins.push(new webpack.optimize.OccurenceOrderPlugin())
  plugins.push(new webpack.optimize.UglifyJsPlugin({
    compress: {
      unused: true,
      dead_code: true,
      warnings: false,
    }
  }))

  return { entrys, plugins }
}

var obj = getEntryAndPlugin()

var webpackConfig = {
  entry: obj.entrys,
  output:{
    path:path.resolve(BUILD_PATH,'js'),
    publicPath: '/', // output.publicPath 表示资源的发布地址，当配置过该属性后，打包文件中所有通过相对路径引用的资源都会被配置的路径所替换。
    filename:'[name].js',
    //hash: true, // 开启hash编码功能
  },
  module:{
    loaders:[
      {
        test:/\.jsx?$/,
        //loaders: ['es3ify', 'babel'],   //加载babel模块
        loaders: ['babel'],   //加载babel模块
        include:APP_PATH,
        exclude:NODE_MODULE_DIR,
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'postcss', 'sass'],
        include:APP_PATH,
        exclude:NODE_MODULE_DIR,
      },
      {
        test: /\.(png|jpg|ico)$/,
        loader: 'url-loader?limit=8192&name=images/[name].[ext]'
      }
    ]
  },
  plugins: obj.plugins,
}

module.exports = webpackConfig
